package com.ruochen.common.base;


import android.content.Intent;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.JsonSyntaxException;
import com.ruochen.common.utils.SerializableSpTools;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.observers.DefaultObserver;
import retrofit2.HttpException;

/**
 * @描述: 访问网络完毕回调
 * @作者: 宋俊 SongJun
 * @时间: 2016/11/11 14:32
 * @版权: 贵州化创云科技
 * @官网: http://www.gzytkj.net/
 */
public abstract class ApiCallback<M> extends DefaultObserver<M> {

    public abstract void onSuccess(M model);

    public abstract void onFailure(int code, String msg);

    private WeakReference<BaseView> backView;

    public ApiCallback(BaseView bv) {
        backView = new WeakReference<>(bv);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        String msg;
        int code = 888;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            code = httpException.code();
            if (code >= 500 && code < 600) {
                msg = "服务器异常";
                code = 801;
            } else if (code >= 400 && code < 500) {
                msg = "无法连接到服务器";
                code = 801;
            } else {
                code = 803;
                msg = "网络不给力";
            }
        } else if (e instanceof UnknownHostException) {
            code = 803;
            msg = "网络不给力";
        } else if (e instanceof SocketTimeoutException) {
            code = 804;
            msg = "连接超时";
        } else if (e instanceof ConnectException) {
            code = 805;
            msg = "连接服务器失败";
        } else if (e instanceof IllegalStateException) {
            code = 806;
            msg = "解析错误";
        } else if (e instanceof JsonSyntaxException) {
            code = 806;
            msg = "解析错误";
        } else if (e instanceof IOException) {
            code = 807;
            msg = "无法连接到网络";
        } else {
            msg = "连接失败";
        }
        if (!NetworkUtils.isConnected()) {
            code = 801;
            msg = "无法连接到网络";
        }
        if (backView != null && backView.get() != null && !backView.get().isFinish()) {
            onFailure(code, msg);
            backView.get().removeCallBack(this);
            backView.clear();
            backView = null;
        }
    }

    @Override
    public void onNext(M model) {
        if (backView != null && backView.get() != null && !backView.get().isFinish()) {
            int code = ((BaseModel) model).getCode();
            if (code == 200) {
                onSuccess(model);
            } else if (code == -8 || code == -9 || code == -5) {//登录失效
                //返回失败信息
                onFailure(BaseConstants.AUTH_FIALURE_CODE, "登录失效");
                if (ActivityUtils.getTopActivity() != null && ActivityUtils.getTopActivity().getClass().getSimpleName().contains("LoginAccountActivity")) {
                    //如果是当前页面是登录页 不做任何处理
                } else {
                    //否则跳转到登录页
                    ActivityUtils.finishAllActivities();
                    SerializableSpTools.clearLoginScope();
                    Intent intent = new Intent("com.ruochen.logisticsscan.action.LOGIN");
                    intent.addCategory("com.ruochen.logisticsscan.category.AUTH_FAILURE");
                    ActivityUtils.startActivity(intent);
                }
            } else {
                onFailure(((BaseModel) model).getCode(), ((BaseModel) model).getMsg());
            }
            backView.get().removeCallBack(this);
            backView.clear();
            backView = null;
        }
    }

    @Override
    protected void onStart() {
        if (!NetworkUtils.isConnected()) {
            if (backView != null && backView.get() != null && !backView.get().isFinish()) {
                onFailure(801, "无法连接到网络");
                cancel();
                backView.get().removeCallBack(this);
                backView.clear();
                backView = null;
            }
        }
    }

    @Override
    public void onComplete() {
        if (backView != null && backView.get() != null && !backView.get().isFinish()) {
            backView.get().removeCallBack(this);
            backView.clear();
            backView = null;
        }
    }

    void cancelRequest() {
        cancel();
    }
}
